package test;

import java.awt.BorderLayout;
import java.awt.Font;
import java.awt.HeadlessException;
import java.awt.MenuItem;
import java.awt.PopupMenu;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.InputEvent;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.util.ArrayList;
import java.util.StringTokenizer;

import javax.print.DocFlavor.INPUT_STREAM;
import javax.swing.AbstractAction;
import javax.swing.Action;
import javax.swing.ActionMap;
import javax.swing.InputMap;
import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JList;
import javax.swing.JMenuItem;
import javax.swing.JPopupMenu;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.KeyStroke;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;
import javax.swing.event.UndoableEditEvent;
import javax.swing.event.UndoableEditListener;
import javax.swing.text.BadLocationException;
import javax.swing.text.Document;
import javax.swing.undo.CannotRedoException;
import javax.swing.undo.CannotUndoException;
import javax.swing.undo.UndoManager;

public class MyPropertiesCreater extends JFrame {
	JTextArea textArea = new JTextArea();
	JButton button = new JButton("run");
	private String actionKey = "action1";
	JScrollPane scrollPane;
	JList jlist;
	ArrayList<MyProperties> keyProperties;

	final UndoManager undo = new UndoManager();
	Document doc = textArea.getDocument();

	public MyPropertiesCreater() throws HeadlessException {
		super("Nhan PropertiesCreator v1.0");
		keyProperties = new ArrayList<MyProperties>();
		String normalTableNameReplacesMent = "sqlBuf.append(businessDBUser).append(\".\");\n";
		keyProperties.add(new MyProperties("SYMPHONIZER_NORMAL_TABLE.",
				normalTableNameReplacesMent));
		String sysTableNameReplacesMent = "sqlBuf.append(basicUser).append(\".\");\n";
		keyProperties.add(new MyProperties("SYMPHONIZER_SYSTEM_TABLE.",
				sysTableNameReplacesMent));

		textArea.setFont(new Font("Courier New", 0, 20));


		// Listen for undo and redo events
		doc.addUndoableEditListener(new UndoableEditListener() {
		    public void undoableEditHappened(UndoableEditEvent evt) {
		        undo.addEdit(evt.getEdit());
		    }
		});

		// Create an undo action and add it to the text component
		textArea.getActionMap().put("Undo",
		    new AbstractAction("Undo") {
		        public void actionPerformed(ActionEvent evt) {
		            try {
		                if (undo.canUndo()) {
		                    undo.undo();
		                }
		            } catch (CannotUndoException e) {
		            }
		        }
		   });

		// Bind the undo action to ctl-Z
		textArea.getInputMap().put(KeyStroke.getKeyStroke("control Z"), "Undo");

		// Create a redo action and add it to the text component
		textArea.getActionMap().put("Redo",
		    new AbstractAction("Redo") {
		        public void actionPerformed(ActionEvent evt) {
		            try {
		                if (undo.canRedo()) {
		                    undo.redo();
		                }
		            } catch (CannotRedoException e) {
		            }
		        }
		    });

		// Bind the redo action to ctl-Y
		textArea.getInputMap().put(KeyStroke.getKeyStroke("control Y"), "Redo");




		final JPopupMenu popupMenu = new JPopupMenu();
		JMenuItem menuItemRun = new JMenuItem("Run appender...");
		popupMenu.add(menuItemRun);

//		textArea.add(popupMenu);

//		textArea.add(popupMenu);

		textArea.addMouseListener(new MouseListener() {

			@Override
			public void mouseReleased(MouseEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mousePressed(MouseEvent e) {
				if(e.getButton() == e.BUTTON3)
				popupMenu.show(e.getComponent(), e.getX(), e.getY());

			}

			@Override
			public void mouseExited(MouseEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseEntered(MouseEvent e) {
				// TODO Auto-generated method stub

			}

			@Override
			public void mouseClicked(MouseEvent e) {
				// TODO Auto-generated method stub

			}
		});

		menuItemRun.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				runAction();

			}
		});

		button.addActionListener(new ActionListener() {

			@Override
			public void actionPerformed(ActionEvent e) {
				runAction();
			}
		});
		Action actionListener = new AbstractAction() {

			@Override
			public void actionPerformed(ActionEvent e) {
				int x = (int) textArea.getCaret().getMagicCaretPosition()
						.getX();
				int y = (int) textArea.getCaret().getMagicCaretPosition()
						.getY();
				scrollPane.setBounds(x, y + 20, 250, 100);
				scrollPane.setVisible(true);
				jlist.setSelectedIndex(0);
				jlist.requestFocus();

			}
		};

		String[] keys = new String[keyProperties.size()];
		for (int i = 0; i < keys.length; i++) {
			keys[i] = keyProperties.get(i).getKey();
		}
		jlist = new JList(keys);
		textArea.setLayout(null);
		scrollPane = new JScrollPane(jlist);
		textArea.add(scrollPane);
		scrollPane.setBounds(0, 0, 100, 50);
		scrollPane.setVisible(false);
		jlist.addKeyListener(new KeyListener() {

			@Override
			public void keyTyped(KeyEvent e) {
				System.out.println((int) e.getKeyChar());
				if ((int) e.getKeyChar() == 10) {
					String dataSelected = (String) jlist.getSelectedValue();
					scrollPane.setVisible(false);
					textArea.requestFocus();
					textArea.getCaretPosition();
					try {
						int pos = textArea.getCaretPosition();
						String before = textArea.getText(0, pos);
						String after = textArea.getText(pos, textArea.getText()
								.length() - (pos));
						String text = before + dataSelected + after;
						textArea.setText(text);
						textArea.setCaretPosition(pos + dataSelected.length());
					} catch (BadLocationException e1) {
						// TODO Auto-generated catch block
						e1.printStackTrace();
					}

				}
			}

			@Override
			public void keyReleased(KeyEvent e) {

			}

			@Override
			public void keyPressed(KeyEvent e) {

			}
		});

		InputMap inputMap = textArea.getInputMap();
		ActionMap actionMap = textArea.getActionMap();
		KeyStroke ctrlSpace = KeyStroke.getKeyStroke(KeyEvent.VK_SPACE,
				InputEvent.CTRL_DOWN_MASK);
		inputMap.put(ctrlSpace, this.actionKey);
		actionMap.put(actionKey, actionListener);

		textArea.requestFocus();

		this.getContentPane().add(new JScrollPane(textArea));
		this.getContentPane().add(button, BorderLayout.NORTH);
		this.setSize(800, 600);
		this.setLocationRelativeTo(null);
		this.setDefaultCloseOperation(EXIT_ON_CLOSE);
		this.setVisible(true);

	}


	public void runAction(){
		StringBuffer s = new StringBuffer();

		String text = textArea.getText();
		StringTokenizer stringTokenizer = new StringTokenizer(text,
				"\n");
		while (stringTokenizer.hasMoreTokens()) {
			String token = stringTokenizer.nextToken();
			token = token.trim();
			token = token.replaceAll("\r", "");
			token = token.toLowerCase();
			StringTokenizer stringTokenizer2 = new StringTokenizer(token, "_");
			String currentPro = "";
			int index = 0;
			while (stringTokenizer2.hasMoreTokens()) {
				String token2 = stringTokenizer2.nextToken();
				if (index != 0) {
					token2 = this.upcaseFirst(token2);
				}
				currentPro += token2;


				index++;
			}
			currentPro = "private String " + currentPro + ";\n";
			s.append(currentPro);

		}


		StringBuffer s2 = new StringBuffer(textArea.getText());
		s2.append(
				"\n ------------------------Kết quả ----------------------\n")
				.append(s.toString());


		textArea.setText(s2.toString());

		textArea.requestFocus();
	}
	public static String upcaseFirst(String token2) {
		if (token2 == null || token2.length() == 0) {
			return "";
		} else {
			String first = token2.charAt(0) + "";
			first = first.toUpperCase();
			String remain = token2.substring(1);
			return first + remain;

		}
	}


	public static void main(String[] args) {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (InstantiationException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalAccessException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (UnsupportedLookAndFeelException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		new MyPropertiesCreater();

	}

}
